package com.rc.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.rc.SplashScreen.SplashScreenActivity;
import com.rc.activity.account.AccountGeneral;
import com.rc.activity.account.GenericAccountService;
import com.rc.activity.dao.tbl_Count;
import com.rc.activity.dao.tbl_User;
import com.rc.activity.provider.Contract;
import com.rc.adapter.DashBoardReceiptAdapter;
import com.rc.adapter.DashBoardReportAdapter;
import com.rc.custom.MyListView;
import com.rc.db.DatabaseSupport;
import com.rc.gcm.Config;
import com.rc.net.NetSupport;
import com.rc.util.Const;
import com.rc.util.NetworkChangeReceiver;
import com.rc.util.Util;
import com.telpoo.frame.ui.BaseActivity;

public class DashBoardScreen extends BaseActivity implements OnClickListener {

	public static final String EXTRA_MESSAGE = "message";
	public static final String PROPERTY_REG_ID = "registration_id";
	public static final String PROPERTY_APP_VERSION = "appVersion";

	private LinearLayout llSnap, llAddExpense, llSettings, llYourProfile,
			llFeedBack;
	private Dialog dialog;

	private DashBoardReportAdapter adpReportType;
	private DashBoardReceiptAdapter adpReceiptType;
	private DashBoardReportAdapter adpTripType;
	private MyListView lvReceiptType, lvReportType, lvTripType;
	private ArrayList<tbl_Count> arrReceiptType = null, arrReportType = null,
			arrTripType = null;
	protected Uri imageUri;// Uri of image capture
	private ReceiptUpdateBroadcast receiptBroadcast;
	private ReportUpdateBroadcast reportBroadcast;
	private TripUpdateBroadcast tripBroadcast;
	private Boolean myReceiptReceiverIsRegistered = false,
			myReportReceiverIsRegistered = false,
			myTripReceiverIsRegistered = false;

	public static void callIntent(Activity ct) {
		Intent it = new Intent(ct, DashBoardScreen.class);
		it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		it.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		ct.startActivity(it);
	}

	NetworkChangeReceiver receiver = new NetworkChangeReceiver();

	@Override
	protected void onStart() {
		super.onStart();

	}

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main_dashboard);

		// register
		llSnap = (LinearLayout) findViewById(R.id.llSnap);
		llSettings = (LinearLayout) findViewById(R.id.llSettings);
		llYourProfile = (LinearLayout) findViewById(R.id.llYourProfile);
		llFeedBack = (LinearLayout) findViewById(R.id.llFeedBack);
		llAddExpense = (LinearLayout) findViewById(R.id.llAddExpense);

		// Register
		lvReceiptType = (MyListView) findViewById(R.id.lvReceiptType);
		lvReportType = (MyListView) findViewById(R.id.lvReportType);
		lvTripType = (MyListView) findViewById(R.id.lvTripType);

		// remove border listview
		lvReceiptType.setDivider(null);
		lvReportType.setDivider(null);
		lvTripType.setDivider(null);

		// funtion
		llAddExpense.setOnClickListener(this);
		llSettings.setOnClickListener(this);
		llSnap.setOnClickListener(this);
		llYourProfile.setOnClickListener(this);
		llFeedBack.setOnClickListener(this);

		// register broadcast
		receiptBroadcast = new ReceiptUpdateBroadcast();
		reportBroadcast = new ReportUpdateBroadcast();
		tripBroadcast = new TripUpdateBroadcast();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (!myReceiptReceiverIsRegistered) {
			registerReceiver(receiptBroadcast, new IntentFilter(
					"update.receipt"));
			myReceiptReceiverIsRegistered = true;
		}
		if (!myReportReceiverIsRegistered) {
			registerReceiver(reportBroadcast, new IntentFilter("update.report"));
			myReportReceiverIsRegistered = true;
		}
		if (!myTripReceiverIsRegistered) {
			registerReceiver(tripBroadcast, new IntentFilter("update.trip"));
			myTripReceiverIsRegistered = true;
		}

		// call request sync
		createSyncAccount(this);

		// Create folder app
		Util.createDirIfNotExists();

		new registerGCM().execute();

		arrReceiptType = DatabaseSupport.getArrReceiptTypes(getResources(),
				DashBoardScreen.this);

		adpReceiptType = new DashBoardReceiptAdapter(DashBoardScreen.this,
				arrReceiptType);
		lvReceiptType.setAdapter(adpReceiptType);
		lvReceiptType.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				ReceiptBox.callIntent(
						DashBoardScreen.this,
						Util.getReceiptTypeByText(DashBoardScreen.this,
								((TextView) lvReceiptType.getChildAt(arg2)
										.findViewById(R.id.txtText)).getText()
										.toString())
								+ "", 1);
			}
		});

		// ReportType
		arrReportType = new ArrayList<tbl_Count>();
		arrReportType = DatabaseSupport.getArrReportTypes(getResources(),
				DashBoardScreen.this);
		adpReportType = new DashBoardReportAdapter(DashBoardScreen.this,
				arrReportType);
		lvReportType.setAdapter(adpReportType);
		lvReportType.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				ReceiptBox.callIntent(
						DashBoardScreen.this,
						((TextView) lvReportType.getChildAt(arg2).findViewById(
								R.id.txtText)).getText().toString(), 3);
			}
		});

		// TripType
		arrTripType = new ArrayList<tbl_Count>();
		arrTripType = DatabaseSupport.getArrTripTypes(getResources(),
				DashBoardScreen.this);
		if (arrTripType == null) {
			return;
		}
		adpTripType = new DashBoardReportAdapter(DashBoardScreen.this,
				arrTripType);
		lvTripType.setAdapter(adpTripType);
		lvTripType.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				ReceiptBox.callIntent(
						DashBoardScreen.this,
						((TextView) lvTripType.getChildAt(arg2).findViewById(
								R.id.txtText)).getText().toString(), 2);
			}
		});

	}

	@Override
	protected void onPause() {
		super.onPause();
		if (myReceiptReceiverIsRegistered) {
			unregisterReceiver(receiptBroadcast);
			myReceiptReceiverIsRegistered = false;
		}
		if (myReportReceiverIsRegistered) {
			unregisterReceiver(reportBroadcast);
			myReportReceiverIsRegistered = false;
		}
		if (myTripReceiverIsRegistered) {
			unregisterReceiver(tripBroadcast);
			myTripReceiverIsRegistered = false;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.llSnap:
			createDialogChoosePhoto();
			break;
		case R.id.llYourProfile:
			YourProfile.callIntent(DashBoardScreen.this);
			break;
		case R.id.llSettings:
			Settings.callIntent(DashBoardScreen.this);
			break;
		case R.id.llAddExpense:
			ReceiptMerchantInfo.callIntentNew(DashBoardScreen.this, true);
			break;
		case R.id.llFeedBack:
			FeedBack.callIntent(DashBoardScreen.this);
			break;
		default:
			break;
		}
	}

	private void createDialogChoosePhoto() {
		dialog = new Dialog(this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_choose_photo);
		LinearLayout llViewAnblum, llTakePicture;
		llViewAnblum = (LinearLayout) dialog.findViewById(R.id.llViewAnblum);
		llTakePicture = (LinearLayout) dialog.findViewById(R.id.llTakePicture);
		llViewAnblum.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(
						Intent.createChooser(intent, "Select Picture"),
						Const.GALLERY_REQUEST);
			}
		});
		llTakePicture.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
				Intent cameraIntent = new Intent(
						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				imageUri = Uri.fromFile(new File(Environment
						.getExternalStorageDirectory(), "receipt"
						+ String.valueOf(System.currentTimeMillis()) + ".jpg"));
				cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
						imageUri);
				startActivityForResult(cameraIntent, Const.CAMERA_REQUEST);
			}
		});
		dialog.show();

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == Const.CAMERA_REQUEST
				&& resultCode == Activity.RESULT_OK) {

			ImageViewScreen.callIntentBitMap(DashBoardScreen.this,
					imageUri.toString());
		} else if (requestCode == Const.GALLERY_REQUEST
				&& resultCode == Activity.RESULT_OK) {
			try {
				// We need to recyle unused bitmaps
				Log.e("adad", data.getData().toString());
				ImageViewScreen.callIntentBitMap(DashBoardScreen.this, data
						.getData().toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	@SuppressLint("NewApi")
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		Intent intent = new Intent(DashBoardScreen.this,
				SplashScreenActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("EXIT", true);
		startActivity(intent);
	}

	private static final String PREF_SETUP_COMPLETE = "12345n";
	public static Account mConnectedAccount;

	public void createSyncAccount(Context context) {
		Log.e("123", "dfgh");
		boolean newAccount = false;
		boolean setupComplete = PreferenceManager.getDefaultSharedPreferences(
				context).getBoolean(PREF_SETUP_COMPLETE, false);
		// Create account, if it's missing. (Either first run, or user has
		// deleted account.)
		mConnectedAccount = GenericAccountService
				.GetAccount(AccountGeneral.ACCOUNT_TYPE);
		AccountManager accountManager = (AccountManager) context
				.getSystemService(Context.ACCOUNT_SERVICE);

		if (accountManager.addAccountExplicitly(mConnectedAccount, null, null)) {
			// Inform the system that this account supports sync
			ContentResolver.setIsSyncable(mConnectedAccount,
					Contract.AUTHORITY, 1);

			ContentResolver.setSyncAutomatically(mConnectedAccount,
					Contract.AUTHORITY, true);
		}

		if (newAccount || !setupComplete) {
			PreferenceManager.getDefaultSharedPreferences(context).edit()
					.putBoolean(PREF_SETUP_COMPLETE, true).commit();
		}
	}

	/**
	 * đăng ký GCM
	 */
	private GoogleCloudMessaging gcm;

	private class registerGCM extends AsyncTask<String, Void, String> {
		String msg = "";

		protected String doInBackground(String... urls) {
			try {
				if (gcm == null) {
					gcm = GoogleCloudMessaging
							.getInstance(DashBoardScreen.this);
				}
				String regid = gcm.register(Config.GOOGLE_SENDER_ID);

				// if (Util.isNetworkActivated(DashBoardScreen.this)) {
				// NetSupport.register_device(DashBoardScreen.this, regid);
				// }

				msg = regid;
				tbl_User objUser = new tbl_User();
				objUser = DatabaseSupport.getTbl_User(DashBoardScreen.this);
				if (objUser == null) {
					return "";
				}
				if (Util.isNetworkActivated(DashBoardScreen.this)) {
					if ("".equals(objUser.getDeviceToken())
							|| "null".equals(objUser.getDeviceToken())
							|| objUser.getDeviceToken() == null) {
						NetSupport.register_device(DashBoardScreen.this, regid);
					}

				}

				// You should send the registration ID to your server over HTTP,
				// so it can use GCM/HTTP or CCS to send messages to your app.
				// The request to your server should be authenticated if your
				// app
				// is using accounts.
				sendRegistrationIdToBackend();

				// For this demo: we don't need to send it because the device
				// will send upstream messages to a server that echo back the
				// message using the 'from' address in the message.

				// Persist the regID - no need to register again.
				storeRegistrationId(DashBoardScreen.this, regid);
			} catch (IOException ex) {
				msg = "";
				// If there is an error, don't just keep trying to register.
				// Require the user to click a button again, or perform
				// exponential back-off.
			}
			Log.e("msg-register-gcm", msg);
			return msg;
		}

		protected void onPostExecute(String result) {

			if ("".equals(result)) {
				return;
			}
			tbl_User objUser = new tbl_User();
			objUser = DatabaseSupport.getTbl_User(DashBoardScreen.this);
			objUser.setDeviceToken(result);
			getContentResolver().update(Contract.CONTENT_URI_USER,
					objUser.getContentValues(), null, null);
			DashBoardScreen.this.getContentResolver().update(
					Contract.CONTENT_URI_USER, objUser.getContentValues(),
					null, null);

		}
	}

	/**
	 * @return Application's version code from the {@code PackageManager}.
	 */
	private static int getAppVersion(Context context) {
		try {
			PackageInfo packageInfo = context.getPackageManager()
					.getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			// should never happen
			throw new RuntimeException("Could not get package name: " + e);
		}
	}

	/**
	 * Stores the registration ID and app versionCode in the application's
	 * {@code SharedPreferences}.
	 * 
	 * @param context
	 *            application's context.
	 * @param regId
	 *            registration ID
	 */
	private void storeRegistrationId(Context context, String regId) {
		final SharedPreferences prefs = getGCMPreferences(context);
		int appVersion = getAppVersion(context);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString(PROPERTY_REG_ID, regId);
		editor.putInt(PROPERTY_APP_VERSION, appVersion);
		editor.commit();
	}

	/**
	 * @return Application's {@code SharedPreferences}.
	 */
	private SharedPreferences getGCMPreferences(Context context) {
		// This sample app persists the registration ID in shared preferences,
		// but
		// how you store the regID in your app is up to you.
		return getSharedPreferences(DashBoardScreen.class.getSimpleName(),
				Context.MODE_PRIVATE);
	}

	private void sendRegistrationIdToBackend() {
		// Your implementation here.
	}

	private class ReceiptUpdateBroadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Log.e("push-update-receipt", "1");
			arrReceiptType = new ArrayList<tbl_Count>();
			arrReceiptType = DatabaseSupport.getArrReceiptTypes(getResources(),
					DashBoardScreen.this);
			adpReceiptType.NotiDB(arrReceiptType);
		}

	}

	private class ReportUpdateBroadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Log.e("push-update-report", "1");
			arrReportType = new ArrayList<tbl_Count>();
			arrReportType = DatabaseSupport.getArrReportTypes(getResources(),
					DashBoardScreen.this);
			adpReportType.NotiDB(arrReportType);
		}

	}

	private class TripUpdateBroadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Log.e("push-update-trip", "1");
			arrTripType = new ArrayList<tbl_Count>();
			arrTripType = DatabaseSupport.getArrTripTypes(getResources(),
					DashBoardScreen.this);
			adpTripType.NotiDB(arrTripType);
		}

	}

}
